package copyengine.resource.file
{
	import copyengine.resource.dto.ResInitDTO;
	import copyengine.resource.dto.ResObjectRequestParamDTO;
	import copyengine.utils.GeneralUtils;

	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;

	public final class CEDataResourceFile extends CEBasicResFile
	{
		private var dataFileLoader:URLLoader;
		private var resFilePath:String;
		private var byteArrayData:ByteArray;


		public function CEDataResourceFile()
		{
			super();
		}

		override protected function doInitialize(_resInitDTO:ResInitDTO):void
		{
			resFilePath = _resInitDTO.filePath;
		}

		override public function getObject(_dto:ResObjectRequestParamDTO):Object
		{
			return byteArrayData;
		}

		override protected function doStartLoadFile():void
		{
			dataFileLoader = new URLLoader();
			dataFileLoader.load(new URLRequest(resFilePath));
			dataFileLoader.dataFormat = URLLoaderDataFormat.BINARY;
			GeneralUtils.addTargetEventListener(dataFileLoader, Event.COMPLETE, onLoaded);
			GeneralUtils.addTargetEventListener(dataFileLoader, ProgressEvent.PROGRESS, loadFileOnProgress);
			GeneralUtils.addTargetEventListener(dataFileLoader, IOErrorEvent.IO_ERROR, loadFileOnError, false, 0, true);
		}

		override protected function releaseLoader():void
		{
			dataFileLoader.close();
			GeneralUtils.removeTargetEventListener(dataFileLoader, Event.COMPLETE, onLoaded);
			GeneralUtils.removeTargetEventListener(dataFileLoader, ProgressEvent.PROGRESS, loadFileOnProgress);
			GeneralUtils.removeTargetEventListener(dataFileLoader, IOErrorEvent.IO_ERROR, loadFileOnError);
			dataFileLoader = null;
		}

		private function onLoaded(e:Event):void
		{
			byteArrayData = dataFileLoader.data as ByteArray;
			byteArrayData.uncompress();
			releaseLoader();
			loadFileComplate();
		}
	}
}
